using Microsoft.EntityFrameworkCore;
using net_work.Config;
using net_work.Data.DTO.Sys;
using net_work.Data.Entity.Sys;
using net_work.IRepository.Sys;

namespace net_work.Repository.Sys;

public class UserRepository(ApplicationDbContext dbContext) : Repository<User>(dbContext), IUserRepository
{
    public async Task<User?> GetByAccountAsync(string userAccount)
    {
        var user = await dbContext.Users
            .Where(u => u.UserAccount == userAccount || u.UserPhone == userAccount || u.UserEmail == userAccount)
            .FirstOrDefaultAsync();

        return user;
    }

    public async Task<long> InsertAsync(UserAddRequest userAddRequest)
    {
        var existingUser = await dbContext.Users
            .IgnoreQueryFilters()
            .Where(u => u.UserAccount == userAddRequest.UserAccount ||
                        (userAddRequest.UserEmail != null && u.UserEmail == userAddRequest.UserEmail) ||
                        u.UserPhone == userAddRequest.UserPhone)
            .FirstOrDefaultAsync();
        if (existingUser != null)
        {
            return -1;
        }

        // 插入用户
        var newUser = new User
        {
            Remark = userAddRequest.Remark,
            UserAccount = userAddRequest.UserAccount,
            UserPassword = userAddRequest.UserPassword,
            UserEmail = userAddRequest.UserEmail,
            UserPhone = userAddRequest.UserPhone,
            UserRole = userAddRequest.UserRole,
            PsnId = userAddRequest.PsnId
        };
        dbContext.Users.Add(newUser);
        await dbContext.SaveChangesAsync();
        return newUser.Id;
    }

    public async Task<bool> UpdateAsync(UserUpdateRequest userUpdateRequest)
    {
        var users = await dbContext.Users
            .IgnoreQueryFilters()
            .Where(u => u.UserAccount == userUpdateRequest.UserAccount ||
                        (userUpdateRequest.UserEmail != null && u.UserEmail == userUpdateRequest.UserEmail) ||
                        u.UserPhone == userUpdateRequest.UserPhone
                        || u.Id == userUpdateRequest.Id)
            .ToListAsync();

        var conflictUser = users.FirstOrDefault(u => u.Id != userUpdateRequest.Id);
        if (conflictUser != null)
        {
            return false;
        }

        var existingUser = users.FirstOrDefault(u => u.Id == userUpdateRequest.Id);
        if (existingUser == null)
        {
            return false;
        }
        
        existingUser.Remark = userUpdateRequest.Remark;
        existingUser.UserAccount = userUpdateRequest.UserAccount;
        existingUser.UserPassword = userUpdateRequest.UserPassword;
        existingUser.UserEmail = userUpdateRequest.UserEmail;
        existingUser.UserPhone = userUpdateRequest.UserPhone;
        existingUser.UserRole = userUpdateRequest.UserRole;
        existingUser.PsnId = userUpdateRequest.PsnId;

        await dbContext.SaveChangesAsync();
        return true;
    }
}